package C046;

import java.util.HashMap;

/**
 * ClassName: C03
 * Package: C046
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/8 09:53
 * @Version 1.0
 * @Since 1.0
 */
public class C03 {
    public static void main(String[] args) {
        int[] arr = {1};
        int k  = 3;
        System.out.println(subarraySum(arr, 0));
    }

    public static int subarraySum(int[] nums, int k) {
        // 获取前缀和数组
        int[] sum = getSumArr(nums);
        // 初始化统计个数map
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 0); // 0前缀和就是-1，个数为0
        int res = 0;
        for (int i = 0; i < sum.length; i++) {
            if(map.containsKey(sum[i] - k)) {
                res += map.get(sum[i] - k);
            }
            map.put(sum[i], map.getOrDefault(sum[i], 0) + 1);
        }
        return res;
    }

    private static int[] getSumArr(int[] arr) {
        int[] res = new int[arr.length];
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            res[i] = sum;
        }
        return res;
    }
}
